package com.liusand.user.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.liusand.entity.dto.SettingDto;
import com.liusand.entity.pojo.Setting;
import com.liusand.user.mapper.SettingMapper;
import com.liusand.user.service.SettingService;
import com.liusand.user.thread.UserThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author :liusha
 * packageName :com.liusand.user.service.Impl
 * fileName :SettingServiceImpl
 * creationTime :2022/12/20 19:22
 */
@Service
public class SettingServiceImpl implements SettingService {

    @Autowired
    private SettingMapper settingMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean modifySetting(SettingDto settingDto) {
        String userId = UserThreadLocalUtil.getId();
        Setting settingInDb = settingMapper.selectSettingByUser(userId);
        int result = 0;
        if(settingInDb == null){
            Setting newSetting = new Setting();
            BeanUtil.copyProperties(settingDto, newSetting);
            newSetting.setId(IdUtil.getSnowflakeNextIdStr());
            newSetting.setUserId(userId);
            result = settingMapper.insertSetting(newSetting);
        }else{
            Setting setting = new Setting();
            BeanUtil.copyProperties(settingDto, setting);
            setting.setId(settingInDb.getId());
            setting.setUpdateTime(LocalDateTime.now());
            result = settingMapper.updateSetting(setting);
        }
        if(result != 1){
            throw new RuntimeException("更新失败");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Setting findSetting() {
        String userId = UserThreadLocalUtil.getId();
        Setting settingInDb = settingMapper.selectSettingByUser(userId);
        if(settingInDb == null){
            Setting newSetting = new Setting();
            newSetting.setId(IdUtil.getSnowflakeNextIdStr());
            newSetting.setUserId(userId);
            int result = settingMapper.insertSetting(newSetting);
            if(result != 1){
                throw new RuntimeException("添加异常");
            }
            settingInDb = settingMapper.selectSettingByUser(userId);
        }
        return settingInDb;
    }
}
